package com.tanhua.manage.service;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tanhua.common.mapper.LogMapper;
import com.tanhua.common.mapper.PublishInfoMapper;
import com.tanhua.common.mapper.UserInfoMapper;
import com.tanhua.common.pojo.Log;
import com.tanhua.common.pojo.PublishInfo;
import com.tanhua.common.pojo.UserInfo;
import com.tanhua.dubbo.server.pojo.Comment;
import com.tanhua.dubbo.server.vo.PageInfo;
import com.tanhua.manage.api.MessageService;
import com.tanhua.manage.vo.CommentQueryParam;
import com.tanhua.manage.vo.CommentVoPlus;
import com.tanhua.manage.vo.LogQueryParam;
import com.tanhua.manage.vo.PageResult;
import lombok.extern.slf4j.Slf4j;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.annotation.Id;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @author 寒
 * @date 2021/6/6
 * @TIME:11:07
 */
@Service
@Slf4j
public class MessageServiceImpl implements MessageService {
    @Autowired
    private LogMapper logMapper;

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private PublishInfoMapper publishInfoMapper;

    @Override
    public PageResult queryLogs(LogQueryParam queryParam) {
        PageResult pageResult = new PageResult();
        try {
            QueryWrapper<Log> query = new QueryWrapper<>();

            Integer page = queryParam.getPage();
            Integer pageSize = queryParam.getPagesize();
            if (page == null) {
                page = 1;
            }
            if (pageSize == null) {
                pageSize = 10;
            }
            pageResult.setPage(page);
            pageResult.setPagesize(pageSize);
            Page<Log> logPage = new Page<>(page, pageSize);
            query.eq("user_id", queryParam.getUid());
            if (queryParam.getSortProp().equals("logTime")) {
                queryParam.setSortProp("log_time");
            }
            if (queryParam.getType() != null) {
                query.eq("type", queryParam.getType());
            }
            if (queryParam.getSortOrder().equals("ascending")) {
                query.orderByAsc(queryParam.getSortProp());
            } else {
                query.orderByDesc(queryParam.getSortProp());
            }
            IPage<Log> logIPage = logMapper.selectPage(logPage, query);
            List<Log> records = logIPage.getRecords();
            if (records == null) {
                return pageResult;
            }
            int conuts = records.size();
            pageResult.setItems(records);
            pageResult.setCounts(conuts);
        } catch (Exception e) {
            log.error("查询数据库错误", e);
        }


        return pageResult;
    }

    @Override
    public PageResult queryComment(CommentQueryParam queryParam) {
        PageResult pageResult = new PageResult();
        try {
            String messageID = queryParam.getMessageID();
            if (messageID == null) {
                return pageResult;
            }
            QueryWrapper<PublishInfo> wrapper = new QueryWrapper<>();
            wrapper.eq("id", messageID);
            PublishInfo publishInfo = publishInfoMapper.selectOne(wrapper);
            if (publishInfo == null) {
                return pageResult;
            }
            Integer page = queryParam.getPage();
            Integer pageSize = queryParam.getPagesize();
            if (page == null) {
                page = 1;
            }
            if (pageSize == null) {
                pageSize = 10;
            }
            pageResult.setPage(page);
            pageResult.setPagesize(pageSize);
            //查询评论表
            PageInfo<Comment> pageInfo = this.queryCommentListAndOrder(publishInfo.getPublishId(), page, pageSize, queryParam.getSortOrder(), queryParam.getSortProp());
            List<Comment> records = pageInfo.getRecords();
            if (CollUtil.isEmpty(records)) {
                return pageResult;
            }
            List<Object> userIdList = CollUtil.getFieldValues(records, "userId");
            //查询用户表
            List<UserInfo> userInfoList = queryUserInfoByUserIdList(userIdList);

            List<CommentVoPlus> result = new ArrayList<>();
            for (Comment record : records) {
                CommentVoPlus commentVo = new CommentVoPlus();
                commentVo.setContent(record.getContent());
                commentVo.setId(record.getId().toHexString());
                commentVo.setCreateDate(record.getCreated());
                commentVo.setUserId(Convert.toInt(record.getUserId()));
                for (UserInfo userInfo : userInfoList) {
                    if (ObjectUtil.equals(record.getUserId(), userInfo.getUserId())) {
                        commentVo.setNickname(userInfo.getNickName());
                        break;
                    }
                }

                result.add(commentVo);
            }

            int conuts = result.size();
            pageResult.setItems(result);
            pageResult.setCounts(conuts);
        } catch (Exception e) {
            log.error("查询数据库错误");
        }

        return pageResult;
    }

    @Override
    public PageInfo<Comment> queryCommentListAndOrder(String publishId, Integer page, Integer pageSize, String order, String sortProp) {
        PageRequest pageRequest = new PageRequest(page, pageSize);
        if (StrUtil.equals(order, "ascending")) {
            pageRequest = PageRequest.of(page - 1, pageSize, Sort.by(Sort.Order.asc(sortProp)));
        } else {
            pageRequest = PageRequest.of(page - 1, pageSize, Sort.by(Sort.Order.desc(sortProp)));
        }

        Query query = Query.query(Criteria.where("publishId").is(new ObjectId(publishId))
                .and("commentType").is(2)
        ).with(pageRequest);
        List<Comment> commentList = this.mongoTemplate.find(query, Comment.class);

        PageInfo<Comment> pageInfo = new PageInfo<>();
        pageInfo.setPageSize(pageSize);
        pageInfo.setPageNum(page);
        pageInfo.setRecords(commentList);

        return pageInfo;
    }


    public List<UserInfo> queryUserInfoByUserIdList(Collection<?> userIdList) {
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("user_id", userIdList);
        List<UserInfo> userInfos = userInfoMapper.selectList(queryWrapper);
        return userInfos;
    }
}

